/**
 * 全局Popup
 */
(function() {
	var scripts = document.getElementsByTagName("script")
	var currentScriptPath = scripts[scripts.length-1].src;
	app.directive('zGlobalDialog',['$rootScope','$http','$compile',function($rootScope,$http,$compile) {
		return {
			restrict:'A',
			link: function(scope,element,attrs,controller){
				$rootScope.alertInfo = function(msg) {
					var newScope = scope.$new();
					newScope.message = msg;
					newScope.level = "panel-primary";
					newScope.size = "modal-sm";
					newScope.title = "提示信息";
					newDialog(newScope);
				};
				
				$rootScope.alertError = function(msg) {
					var newScope = scope.$new();
					newScope.message = msg;
					if(angular.isArray(msg)){
						newScope.isArray = true;
					}else{						
						newScope.isArray = false;
					}
					newScope.level = "panel-danger";
					newScope.size = "modal-sm";
					newScope.title = "发生错误";
					newDialog(newScope);
				};
				
				$rootScope.alertWarning = function(msg) {
					var newScope = scope.$new();
					newScope.message = msg;
					if(angular.isArray(msg)){
						newScope.isArray = true;
					}else{						
						newScope.isArray = false;
					}
					newScope.level = "panel-warning";
					newScope.size = "modal-sm";
					newScope.title = "注意";
					newDialog(newScope);
				};
				
				$rootScope.alertConfirm = function(msg,confirmCB,cancelCB) {
					var newScope = scope.$new();
					newScope.message = msg;
					newScope.level = "panel-warning";
					newScope.size = "modal-sm";
					newScope.title = "请确认";
					newScope.isConfirm = true;
					newScope.confirm = function() {
						if(confirmCB) {
							confirmCB();
						}
					};
					newScope.cancel = function() {
						if(cancelCB) {
							cancelCB();
						}
					}
					newDialog(newScope);
				};
				
				var newDialog = function(newScope) {
					$http.get(currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1) + "globalDialog.html").success(function(data, status, headers, config) {
						var contentHTML = $compile(data)(newScope);
						var dialog = $(contentHTML).appendTo(element);
						dialog.on('hidden.bs.modal',function(e) {
							$(e.currentTarget).remove();
						});
						if(dialog.length>1) {
							console.log("模板必须只能有一个root标签");
						}
						if(element.context.tagName == "BODY") {
						}
						dialog.modal({backdrop:'static',show:true});
//						dialog.modal('show');
					}).error(function(data, status, headers, config) {
						console.log("加载模板模板失败");
					});
				}
				
			}
		};
	}]);
}());